package com.example.broadcastbestpractice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

public class BaseActivity extends AppCompatActivity {
    //这个是该程序中的所有活动的父类
    // 接收一个广播并且弹出一个UI
    LocalBroadcastManager localBroadcastManager;//特别注意这个是静态实例获取
    //广播必须的过滤器和相应的接收器
    IntentFilter intentFilter;
    ForcedOfflineReceiver receiver;
    @Override
    protected void onStart() {
        super.onStart();
        UtilActivityController.addActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter = new IntentFilter(UtilBroadcastString.FORCED_OFFLINE);
        receiver = new ForcedOfflineReceiver();
        localBroadcastManager.registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        localBroadcastManager.unregisterReceiver(receiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UtilActivityController.remove(this);

    }
    // 广播接收器
    class ForcedOfflineReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"你已接收到广播📢！",Toast.LENGTH_SHORT).show();
            // 回顾Ui编程的部分
            AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);//特别注意这个context，上下文，之前直接用receive中的context为参，但是死活弹不出来；dialog是需要根据实际的activity存在的
            builder.setTitle("Warning:").setCancelable(false).setMessage("你的账号在异地登陆，被迫强制下线！");
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 下线所有activity
                    UtilActivityController.removeAll();
                    Toast.makeText(context,"你已成功下线！",Toast.LENGTH_SHORT).show();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }

}
